//
//  LS_CollectionViewHorizontaLayout.m
//  breadPro
//
//  Created by 刘文超 on 2019/7/10.
//  Copyright © 2019 刘文超. All rights reserved.
//

#import "LS_CollectionViewHorizontaLayout.h"
@interface LS_CollectionViewHorizontaLayout()<UICollectionViewDelegateFlowLayout>
@property(nonatomic,strong)NSMutableArray *allAttributes;
@end
@implementation LS_CollectionViewHorizontaLayout
-(instancetype)init
{
    if (self = [super init]) {
    }return self;
}
- (void)prepareLayout

{
    [super prepareLayout];
    
    self.allAttributes = [NSMutableArray array];
    NSInteger sections = [self.collectionView numberOfSections];
    
    for (int i = 0; i < sections; i++)
    {
        NSMutableArray * tmpArray = [NSMutableArray array];
        NSUInteger count = [self.collectionView numberOfItemsInSection:i];
        for (NSUInteger j = 0; j<count; j++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:j inSection:i];
            UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
            [tmpArray addObject:attributes];
        }
        [self.allAttributes addObject:tmpArray];
    }
    
}
- (CGSize)collectionViewContentSize
{
    return [super collectionViewContentSize];
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath

{
    
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    //每一组cell为一行
    NSInteger c = indexPath.section ;
    NSInteger a = indexPath.row % self.itemCountPerRow;
    NSInteger b = indexPath.row / self.itemCountPerRow;
    attributes.frame = CGRectMake(self.itemSize.width*a + c*ScreenWidth , self.itemSize.height*b, self.itemSize.width, self.itemSize.height);
    return attributes;
    
    
    
}
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect

{
    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    NSMutableArray *tmp = [NSMutableArray array];
    for (UICollectionViewLayoutAttributes *attr in attributes) {
        for (NSMutableArray *attributes in self.allAttributes)
        {
            for (UICollectionViewLayoutAttributes *attr2 in attributes) {
                if (attr.indexPath.item == attr2.indexPath.item) {
                    [tmp addObject:attr2];
                    break;
                }
            }
        }
    }
    return tmp;
    
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}
@end
